<?php
namespace app\admin\controller;

use app\api\controller\KbxOrder;
use app\api\model\SupplierTravelGuides;
use think\Request;
use think\Validate;
use app\api\controller\Common as CommonApi;

class Travelguides extends User{
    protected $validate = null;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->validate = new Validate([
            'supplier_admin_id'=>'require',
            'category'=>'require',
            'title'=>'require',
            'content'=>'require',
            'cover_img'=>'require',
        ],[
            'supplier_admin_id.require'=>'请选择供应商',
            'category.require'=>'请选择分类',
            'title.require'=>'请添加攻略标题',
            'content.require'=>'请添加攻略内容',
            'cover_img.require'=>'请添加缩略图',
        ]);
    }

    //列表
    public function guidelist(Request $request)
    {
        //供应商的超级管理员
        list($supplier) = (new Product())->getAllSupplierList();
        $this->assign('supplier_admins',$supplier);

        $category = (new SupplierTravelGuides())->getCategoryType();
        $this->assign('category',$category);

        return $this->fetch();
    }

    public function tableData(Request $request){

        $keyword = $request->param('keyword','');
        $supplier_id = $request->param('supplier_id','');
        $category = $request->param('category','');
        $page = $request->param('page',1);
        $pageLimit = $request->param('limit',15);
        $where['is_delete'] = 0;
        if(!empty($keyword)) $where['id|title|description'] = ['like','%'.$keyword.'%'];
        if(!empty($supplier_id)){
            $supplier_admin_ids = (new CommonApi())->getSupplierAdminIdsByCompanyId($supplier_id);
            $where['supplier_admin_id'] = ['in',$supplier_admin_ids];
        }
        if(!empty($category)) $where['category'] = $category;
        $data = (new SupplierTravelGuides())->listGuide($where,$page,$pageLimit);

        return [
            'code'=>0,
            'msg'=>'',
            'count'=>$data['totalCount'] ?? 0,
            'data'=>$data['list'] ?? []
        ];
    }

    //创建页面
    public function create_guide()
    {
        $poilist = db('poi')->field('id,name')->where(['deleted'=>0])->select();
        $this->assign('poilist',$poilist);
        //供应商的超级管理员
        $supplier_admins = $this->supplierAdminList();
        $this->assign('supplier_admins',$supplier_admins);

        $category = (new SupplierTravelGuides())->getCategoryType();
        $this->assign('category',$category);

        return $this->fetch();
    }

    //更新页面
    public function update_guide(Request $request)
    {
        $id = $request->param('id',0);
        if(empty($id)) return $this->error('请求错误');
        //$supplier_admin_ids = (new Common())->getSupplierCompanyAdminIDs();
        $info = (new SupplierTravelGuides())->infoGuide($id);
        if(empty($info)) return $this->error('权限不足或资源不存在');

        $this->assign('article',$info);

        $poilist = db('poi')->field('id,name')->where(['deleted'=>0])->select();
        $this->assign('poilist',$poilist);
        //供应商的超级管理员
        $supplier_admins = $this->supplierAdminList();
        $this->assign('supplier_admins',$supplier_admins);
        $category = (new SupplierTravelGuides())->getCategoryType();
        $this->assign('category',$category);
        return $this->fetch();
    }

    //ajax创建
    public function create_guide_ajax(Request $request)
    {
        if(!$request->isPost()){
            return $this->error('请以POST方式提交！');
        }
        $post = $request->post();
        if(!empty($_POST['content'])) $post['content'] = htmlspecialchars($_POST['content']);
        if(!$this->validate->check($post)){
            return $this->error($this->validate->getError());
        }
        $result = (new SupplierTravelGuides())->createGuide($post);
        if(!is_array($result)){
            return $this->error($result);
        }else{
            //推送到订单系统
            //获取新增ID和供应商信息
//            $guideId = $result['id'];
            $supplierId = (new CommonApi())->getSupplierAdminInfo($post['supplier_admin_id'])['company_id'] ?? '';
            if(empty($supplierId)) return false;
            (new KbxOrder())->createTravelGuideToKbx($result['id'],$result['category'],$supplierId);
            return $this->success('success');
        }
    }

    //ajax更新
    public function update_guide_ajax(Request $request)
    {
        if(!$request->isPost()){
            return $this->error('请以POST方式提交！');
        }
        $post = $request->post();
        if(!empty($_POST['content'])) $post['content'] = htmlspecialchars($_POST['content']);
        if(!$this->validate->check($post)){
            return $this->error($this->validate->getError());
        }
        $id = $request->post('id',0);
        if(empty($id)) return $this->error('请求错误');
//        $supplier_admin_ids = (new Common())->getSupplierCompanyAdminIDs();
        $info = (new SupplierTravelGuides())->infoGuide($id);
        if(empty($info)) return $this->error('权限不足或资源不存在');

        $result = (new SupplierTravelGuides())->saveGuide($id,$post);
        if(!is_array($result)){
            return $this->error($result);
        }else{
            if(!empty($post['category']) && !empty($info['category'])
                && $post['category'] != $info['category']){
                $fromCtegory = $info['category'];
                $toCategory = $post['category'];
                //推送到订单系统
                $supplierId = (new CommonApi())->getSupplierAdminInfo($info['supplier_admin_id'])['company_id'] ?? '';
                if(empty($supplierId)) return false;
                (new KbxOrder())->updateTravelGuideToKbx($result['id'],$fromCtegory,$toCategory,$supplierId);
            }

            return $this->success('success');
        }
    }

    //ajax更新
    public function update_guide_sort(Request $request)
    {
        if(!$request->isPost()){
            return $this->error('请以POST方式提交！');
        }
        $id = $request->post('id',0);
        $sort_num = $request->post('sort_num',0);
        if(empty($id)) return $this->error('缺少ID');
        if(empty($sort_num)) return $this->error('缺少权重数据');
//        $supplier_admin_ids = (new Common())->getSupplierCompanyAdminIDs();
        $info = (new SupplierTravelGuides())->infoGuide($id);
        if(empty($info)) return $this->error('权限不足或资源不存在');

        $result = (new SupplierTravelGuides())->saveGuide($id,$request->post());
        if(!is_array($result)){
            return $this->error($result);
        }else{

            return $this->success('success');
        }
    }

    //删除
    public function delete_guide(Request $request)
    {
        if(!$request->isPost()){
            return $this->error('请以POST方式提交！');
        }
        $id = $request->post('id',0);
        if(empty($id)) return $this->error('请求错误');
//        $supplier_admin_ids = (new Common())->getSupplierCompanyAdminIDs();
        $info = (new SupplierTravelGuides())->infoGuide($id);
        if(empty($info)) return $this->error('权限不足或资源不存在');

        $result = (new SupplierTravelGuides())->deleteGuide($id);
        if(!is_array($result)){
            return $this->error($result);
        }else{
            //推送到订单系统
            $supplierId = (new CommonApi())->getSupplierAdminInfo($info['supplier_admin_id'])['company_id'] ?? '';
            if(empty($supplierId)) return false;
            (new KbxOrder())->deleteTravelGuideToKbx($id,$info['category'],$supplierId);

            return $this->success('success');
        }
    }

    public function supplierAdminList($is_super=false)
    {
        //供应商的超级管理员
        $where['is_use'] = 1;
        if($is_super) $where['is_super'] = 1;
        $supplier_admins = db('supplier_admin')
            ->where($where)
            ->select();
        if($is_super) return $supplier_admins;
        //添加主次前缀
        foreach ($supplier_admins as $key=>$value){
            $supplier_admins[$key]['supplier_name'] = ($value['is_super'] > 0 ?
                    '(主)' : '(子)').' '.$value['supplier_name'];
        }
        return $supplier_admins;
    }



}